package com.leantech.android.browser.ui.browser

import android.content.Context
import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.leantech.android.browser.browser.TabController
import com.leantech.android.browser.databinding.LayoutTabPreviewBinding
import com.leantech.android.browser.skin.SkinManager
import com.leantech.android.browser.ui.browser.adapter.TabPreviewAdapter
import com.leantech.android.browser.ui.browser.viewmodel.BrowserTabViewModel
import com.leantech.android.browser.ui.browser.viewmodel.BrowserViewModel
import com.leantech.android.browser.utils.onThrottleClick
import com.leantech.android.browser.utils.show
import com.leantech.android.browser.utils.toast
import com.qmuiteam.qmui.kotlin.dip
import com.qmuiteam.qmui.util.QMUIStatusBarHelper
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.activityViewModel

class TabPreviewFragment : Fragment() {

    private lateinit var previewTabItemCallback: TabPreviewAdapter.PreviewTabItemCallback
    private lateinit var tabController: TabController

    private lateinit var previewBinding: LayoutTabPreviewBinding
    private lateinit var tabPreviewAdapter: TabPreviewAdapter

    private val tabViewModel by activityViewModel<BrowserTabViewModel>()
    private val browserViewModel by activityViewModel<BrowserViewModel>()

    private val KEY_ITEM_STYLE = "ItemStyle"

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is TabPreviewAdapter.PreviewTabItemCallback) {
            previewTabItemCallback = context
        } else {
            throw IllegalStateException("activity must implement TabPreviewAdapter.PreviewTabItemCallback")
        }

        if (context is TabController) {
            tabController = context
        } else {
            throw IllegalStateException("activity must implement TabController")
        }

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?,
    ): View? {
        previewBinding = LayoutTabPreviewBinding.inflate(inflater, container, false)
        return previewBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupTabPreview()
        subscribeFlow()
    }

    private fun setupTabPreview() {
        previewBinding.btnCloseAll.onThrottleClick {
            tabController.removeAllTab()
        }
        previewBinding.btnPrivacyBrowse.onThrottleClick {
            val currentPrivacyMode = browserViewModel.currentPrivacyMode()
            browserViewModel.switchPrivacyMode(!currentPrivacyMode)
            if (!currentPrivacyMode) {
                toast("已开启无痕浏览")
            } else {
                toast("已关闭无痕浏览")
            }
        }
        previewBinding.btnNewTab.onThrottleClick {
            tabController.newTab("")
            tabController.exitPreview()
        }
        previewBinding.btnReturn.onThrottleClick {
            resumeActivityStatusBar()
            tabController.exitPreview()
        }

        tabPreviewAdapter = TabPreviewAdapter(previewTabItemCallback)
        initRecycler()
    }

    private fun initRecycler() {
        val itemType = TabPreviewAdapter.ITEM_STYLE_GRID

        val itemDecoration = object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State,
            ) {
                val position = parent.getChildAdapterPosition(view)
                if (position % 2 == 0) {
                    outRect.right = dip(14)
                    outRect.left = dip(6)
                } else {
                    outRect.left = dip(14)
                    outRect.right = dip(6)
                }
                outRect.bottom = dip(12)
            }
        }

        with(previewBinding.previewTabRecyclerView) {
            removeAllViews()
            adapter = tabPreviewAdapter
            tabPreviewAdapter.setItemStyle(itemType)
            layoutManager = GridLayoutManager(requireContext(), 2, RecyclerView.VERTICAL, true)
            addItemDecoration(itemDecoration)
        }
    }

    private fun subscribeFlow() {
        viewLifecycleOwner.lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                launch {
                    tabViewModel.previewItemFlow.collectLatest {
                        val data = it.reversed()
                        tabPreviewAdapter.submitList(data)
                    }
                }

                launch {
                    browserViewModel.privacyModeFlow.collectLatest { on ->
                        updateUI(on)
                    }
                }
            }
        }
    }

    private fun resumeActivityStatusBar() {
        if (SkinManager.isDarkSkin(requireContext())) {
            QMUIStatusBarHelper.setStatusBarDarkMode(requireActivity())
        } else {
            QMUIStatusBarHelper.setStatusBarLightMode(requireActivity())
        }
    }

    private fun updateUI(privacyModeOn: Boolean) {
        previewBinding.privacyBackground.show(privacyModeOn)
        previewBinding.btnSwitchStyle.isSelected = privacyModeOn
        previewBinding.btnCloseAll.isSelected = privacyModeOn
        previewBinding.btnPrivacyBrowse.isChecked = privacyModeOn
        previewBinding.btnNewTab.isSelected = privacyModeOn
        previewBinding.btnReturn.isSelected = privacyModeOn
        if (privacyModeOn) {
            QMUIStatusBarHelper.setStatusBarDarkMode(requireActivity())
        } else {
            resumeActivityStatusBar()
        }
    }
}